package cn.fldong.employee.servlet;

import cn.fldong.employee.dao.EmployeeDao;
import cn.fldong.employee.dao.UserDao;
import cn.fldong.employee.entity.EmployeeEntity;
import cn.fldong.employee.entity.UserEntity;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebServlet("/userLogin")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 1.获取请求参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        // 2.判断参数是否为空，如果为空，则跳转到登录失败页面
        // 这里不能相信用户输入的任何信息，需要做好参数校验
        if (username == null || password == null) {
            resp.sendRedirect("fail.html");
            return;
        }
        // 3.查询数据库，判断用户名和密码是否匹配
        // 这里使用UserDao来查询数据库
        UserDao userDao = new UserDao();
        UserEntity user =  userDao.queryUserByUsername(username);
        // 4.如果匹配成功，则将用户名存入session，并跳转到首页页面
        if (user == null) {
            resp.sendRedirect("fail.html");
            return;
        }
        String dbPass = user.getPassword();
        if (dbPass.equals(password)) {
            req.getSession().setAttribute("username", username);
            resp.sendRedirect("index.jsp");
        } else {
            resp.sendRedirect("fail.html");
        }
    }
}
